from ..base_downloader import *
from ..base_downloader_firefox import BaseDownloaderFirefox
from ..base_downloader_chrome import BaseDownloaderChrome


class Task36(BaseDownloaderFirefox):
    def login(self):
        username_field = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.NAME, "txtUser"))
        )
        password_field = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.NAME, "txtPass"))
        )
        username_field.send_keys(self.username)
        password_field.send_keys(self.password)

        self.driver.find_element(By.ID, "Ibtn_ok").click()

        self.random_sleep(0.5)
        self.accept_alert_dialog()
        self.random_sleep(1.5)

    def retrieve_data(self):
        self.click_query_button()       
        self.set_start_and_end_dates()
        self.click_retrieve_button()

    def click_query_button(self):
        try:
            WebDriverWait(self.driver, 10).until(
                EC.frame_to_be_available_and_switch_to_it((By.ID, "BoardTitle"))
            )
            self.random_sleep(3)
            query_button = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.ID, "leftNb_I2i1_T"))
            )
            query_button.click()
            self.random_sleep(3)
        except Exception as e:
            logger.exception(f"An error occurred while clicking the query button: {e}")

    def set_start_and_end_dates(self): 
        self.driver.switch_to.default_content()
        self.random_sleep(3)
        WebDriverWait(self.driver, 10).until(
            EC.frame_to_be_available_and_switch_to_it((By.ID, "frmright"))
        )
        self.random_sleep(3)  
        
        start_date_input = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located(
                (By.NAME, "staDate")
            )
        )
        start_date_input.clear()  
        start_date_input.send_keys(self.start_date)
        self.random_sleep(3)  

        end_date_input = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located(
                (By.NAME, "endDate")
            )
        )
        end_date_input.clear()
        end_date_input.send_keys(self.end_date)

        self.capture_screenshot()

    def click_retrieve_button(self):
        try:
            self.random_sleep(3)  
            retrieve_button = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.ID, "btnQuery"))
            )
            retrieve_button.click()
        except Exception as e:
            logger.exception(f"An error occurred while clicking the retrieve button: {e}")

    def export_excel(self):
        self.capture_screenshot()
        self.random_sleep(3)  
        export_button = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable((By.ID, "lbtnExport2"))
        )
        export_button.click()
        downloaded_file = self.get_latest_downloaded_file()

        new_file_name = f"{self.site_name}_exported_click_button.xlsx"
        destination_path = os.path.join(self.task_download_dir, new_file_name)
        
        process_downloaded_file(downloaded_file, destination_path)
        logger.info(f"Processed and saved file to: {destination_path}")
        
        self.random_sleep(8)
        self.delete_downloaded_files()

    def download_file(self):
        #self.page_html_to_excel()  # One way to download the Excel file
        self.export_excel()        # Another way to download the Excel file; use either method

    def delete_downloaded_files(self):
        """Delete the original downloaded file after processing."""
        try:
            downloaded_file = self.get_latest_downloaded_file()
            if os.path.exists(downloaded_file):
                os.remove(downloaded_file)
                logger.info(f"Deleted original downloaded file: {downloaded_file}")
        except Exception as e:
            logger.error(f"Error deleting downloaded file: {e}")